<?php
/**
 * Created by PhpStorm.
 * User: spatra
 * Date: 14-11-8
 * Time: 上午10:11
 */

namespace Teacher;

use Illuminate\Support\Facades\Input;

class LessonController extends \LessonController
{
    public function index()
    {
        $condName = Input::get('cond', 'all');
        $respData = $this->getIndexByCond($condName);

        return \Response::json($respData);
    }

    protected function getIndexByCond($condName){

        $currIndexMethod = $condName. 'Index';
        if ( method_exists($this, $currIndexMethod) ) {
            return $this->$currIndexMethod();
        }
        return $this->allIndex();
    }

    protected function allIndex()
    {
        return \Lesson::all();
    }

    protected function mineIndex()
    {
        return \Auth::user()['createLessons'];
    }

    public function store(){
        $postData = \Input::all();
        $postData['teacher_id'] = \Auth::user()['id'];

        $cover = \Input::get('cover', null);
        if( $cover ){
            $newCoverName = $this->getNewCoverName();
            $img = \Image::make(public_path().'/temp/'. $cover);
            $img->resize(320, 240);
            $img->save(public_path().'/image/lesson-cover/'. $newCoverName);
            $postData['cover'] = $newCoverName;
        }

        try{
            $add = \Lesson::create($postData);
            return \Response::json([
                'id'=>$add['id']
            ]);

        }catch (\Exception $err){
            return \Response::make('error', 401);
        }

    }

    protected function getNewCoverName()
    {
        $lessonName = \Input::get('name');
        $coverName = \Input::get('cover');

        return $lessonName . $coverName;
    }
}